<template>
  <div
    class="page-module"
    v-for="(item, index) in list"
    :key="item.site_id"
    draggable="true"
    @dragstart="drag($event, index)"
    @drop="drop($event, index)"
    @dragover="allowDrop($event)"
  >
    <div class="page-module-icon">
      <menu-outlined />
    </div>
    <div class="page-module-list">
      <div class="page-module-list-info">
        <div class="page-module-list-info-left">
          <div class="page-module-list-info-left-icon">
            <a-image
              width="37.6px"
              height="39.85px"
              class="w-[-webkit-fill-available] object-contain"
              :src="getIcon(item)"
              :fallback="defaultImage"
            />
          </div>
          <div class="page-module-list-info-left-content">
            <div class="title ellipsis-text">
              <Tooltip :str="item.site_name" width="300px" />
            </div>
            <div class="arguments">
              <span
                >ID:{{ item.site_id }}<copy-outlined class="text-[#0083ff] ml-[8px]" @click="() => copy(item.site_id)"
              /></span>
              <span>类型：{{ item.site_type == 1 ? '种源资源' : '外部资源' }}</span>
              <span>创建人：{{ item.created_by || '-' }}</span>
              <span>创建时间：{{ formatToDateTime(+item.created_at * 1000) }}</span>
            </div>
          </div>
        </div>
        <div class="page-module-list-info-right">
          <span class="common-btn width-88" @click="handleManage(item)">管理内容</span>
          <span class="common-btn width-58" @click="updateSite(item.site_id)">编辑</span>
          <span
            class="common-btn width-58"
            @click="deleteSite(item.site_id)"
            :class="type === 1 ? 'common-del' : 'common-active'"
            >删除</span
          >
        </div>
      </div>
      <div class="page-module-list-total">
        <div class="page-module-list-total-type">
          <div class="page-module-list-total-type-item">
            <div class="item-img">
              <i class="iconfont icon-yingpian" />
            </div>
            <span class="item-text">影片数量:</span>
            <span class="item-num">{{ formatNumber(Number(item.site_video_count)) }}</span>
          </div>
          <div class="page-module-list-total-type-item">
            <div class="item-img">
              <i class="iconfont icon-tuji" />
            </div>
            <span class="item-text">图集数量:</span>
            <span class="item-num">{{ formatNumber(Number(item.site_picture_count)) }}</span>
          </div>
          <div class="page-module-list-total-type-item">
            <div class="item-img">
              <i class="iconfont icon-wenzhang" />
            </div>
            <span class="item-text">文章数量:</span>
            <span class="item-num">{{ formatNumber(Number(item.site_article_count)) }}</span>
          </div>
          <div class="page-module-list-total-type-item">
            <div class="item-img">
              <i class="iconfont icon-caiji" />
            </div>
            <span class="item-text">采集中任务:</span>
            <span class="item-num">{{ formatNumber(Number(item.site_task_count)) }}</span>
          </div>
        </div>
        <div class="page-module-list-total-switch">
          <a-switch
            v-model:checked="item.site_status"
            :checkedValue="1"
            :unCheckedValue="2"
            @click="(checked:any) => editStatus(checked, item)"
          />
        </div>
      </div>
    </div>
  </div>
  <!-- 禁用对话框 -->
  <modal-view
    title="提示"
    v-model:visible="disabledVisible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="disableConfirm"
    @cancel="disableCancel"
  >
    <span>{{ type === 1 ? disabledText : activeText }}</span>
  </modal-view>
  <!-- 删除对话框 -->
  <modal-view
    title="提示"
    v-model:visible="deleteVisible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="deleteConfirm"
    @cancel="deleteCancel"
  >
    <span>{{ deleteText }}</span>
  </modal-view>
</template>
<script lang="ts" setup>
import type { SiteItem } from '@/types/site/site'
import { ref, computed, toRefs, inject, nextTick } from 'vue'
import useStore from '@/stores'
import router from '@/router'
import { formatNumber, formatToDateTime } from '@/utils/format'
import ModalView from '@/components/components/modal/ModalView.vue'
import Tooltip from '@/components/components/Tooltip.vue'
import { message } from 'ant-design-vue'
import { storage } from '@/utils/storage'
import useClipboard from 'vue-clipboard3'
import apis from '@/apis'
import defaultImage from '@/assets/icon/defaultImage.png'
const baseUrl: any = inject('baseUrl')
console.log('baseUrl: ', baseUrl)
const { toClipboard } = useClipboard()
const {
  site: { edit_status, update, del }
} = apis
const { permission } = useStore()
interface SiteData {
  type: number
  list: SiteItem[]
}
const deleteId = ref()
const emit = defineEmits(['updateList'])
const props = defineProps<SiteData>()
const { list, type } = toRefs(props)
console.log('list: ', list)
const disabledVisible = ref(false)
const deleteVisible = ref(false)
const isChecked = ref(1) //是否禁用
const disabledId = ref() //禁用id

const activeText = ref('确定要启用该站点吗？')
const disabledText = ref('禁用站点可能导致使用该站点的应用内容为空，确定要禁用该站点吗？')
const deleteText = ref('删除站点不可恢复，可能导致使用该站点的应用内容为空，确定要删除吗？')
const drag = (event: any, index: number) => {
  event.dataTransfer.setData('index', index)
}
//排序方法
const orderFunc = (currentIndex: number) => {
  const { site_name, site_icon, site_icon_type, site_introduction, site_status, site_id, site_order } =
    list.value[currentIndex]
  const params = {
    site_name,
    site_icon,
    site_icon_type,
    site_introduction,
    site_status,
    site_id,
    site_order
  }
  update(params).then(() => {
    message.success('排序成功')
  })
}
const drop = (event: any, index: number) => {
  event.preventDefault()
  let startIndex = +event.dataTransfer.getData('index')
  let currentIndex: number = +index
  console.log('start', startIndex)
  console.log('drop', currentIndex)

  if (startIndex - currentIndex > 0) {
    console.log('要拖拽的元素的索引 大于 当前位置的元素的索引')
    list.value[startIndex].site_order = list.value[currentIndex].site_order
    list.value.splice(currentIndex, 0, list.value[startIndex])
    console.log('删除' + (startIndex + 1))
    list.value.splice(startIndex + 1, 1)
    orderFunc(currentIndex)
  } else if (startIndex - currentIndex < 0) {
    console.log('要拖拽的元素的索引  小于 当前位置的元素的索引')
    list.value.splice(currentIndex + 1, 0, list.value[startIndex])
    list.value.splice(startIndex, 1)

    orderFunc(currentIndex)
  } else {
    console.log('什么也不用做')
  }
  console.log('list.value: ', list.value)
  // list.value.forEach((item, index) => {
  //   item.site_order = (index + 1).toString()
  // })
  console.log(list.value[currentIndex], 'list.value[currentIndex]')
}
const allowDrop = (event: any) => {
  event.preventDefault()
}
// 复制站点ID
const copy = async (id: string) => {
  try {
    await toClipboard(id)
    message.success('复制成功')
  } catch (e) {
    console.error(e)
  }
}
//内容管理
const handleManage = (item: SiteItem) => {
  nextTick(() => {
    console.log('item: ', item.site_name)
    permission.setSiteName(item.site_name)
    permission.setSiderType('SITE')
    router.push({ name: 'FilmManage' })
    storage.set('siteId', item.site_id)
    storage.set('siteType', item.site_type)
  })
}
//根据类型获取图片
const getIcon = computed(() => (item: SiteItem) => {
  if (item.site_icon_type === 1) return baseUrl + item.site_icon
  return item.site_icon
})
//编辑站点
const updateSite = (id: string) => {
  router.push({ name: 'EditSite', query: { id: id } })
}
//删除站点
const deleteSite = (id: string) => {
  deleteId.value = id
  if (type.value === 1) {
    return message.warning('启用中站点不能删除！')
  } else {
    deleteVisible.value = true
  }
}

//禁用相关事件
const editStatus = (checked: number, item: any) => {
  if (type.value === 1) {
    disabledVisible.value = true
    isChecked.value = checked
    disabledId.value = item.site_id
  } else {
    const data = {
      type: 1,
      status: checked,
      id: [item.site_id]
    }
    edit_status(data).then(() => {
      message.success('启用成功')
      disabledVisible.value = false
      emit('updateList')
    })
  }
}
//禁用站点
const disableConfirm = (value: any) => {
  const data = {
    type: 1,
    status: isChecked.value,
    id: [disabledId.value]
  }
  edit_status(data).then(() => {
    message.success('禁用成功')
    disabledVisible.value = value
    emit('updateList')
  })
}
const disableCancel = () => {
  disabledVisible.value = false
  emit('updateList')
}
//删除相关事件
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  del({ site_id: deleteId.value }).then(() => {
    message.success('站点删除成功')
    deleteVisible.value = value
    emit('updateList')
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
</script>

<style lang="less" scoped>
.ellipsis-text {
  max-width: 300px !important;
  white-space: nowrap;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}

.common-btn {
  height: 32px;
  line-height: 18px;
  padding: 6px 14px;
  box-sizing: border-box;
  border: 1px solid #d9d9d9;
  margin-left: 16px;
  font-size: 14px;
  color: #262626;
  border-radius: 6px;
}

.common-active {
  color: #fe4c4d;
  background: rgba(254, 76, 77, 0.08);
  border: 1px solid rgba(254, 76, 77, 1);
}

.common-del {
  color: #f0aaaa;
  background: rgba(254, 76, 77, 0.08);
  border: 1px solid #f4c2bf;
}

.page-module:hover .page-module-icon {
  visibility: visible;
}

.page-module:hover {
  box-shadow: 1px 1px 10px 0px rgba(0, 0, 0, 0.15);
}

.page-module {
  width: 100%;
  min-height: 144px;
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  border: 1px solid rgba(217, 217, 217, 1);

  border-radius: 6px;
  cursor: pointer;

  &-icon {
    width: 40px;
    text-align: center;
    visibility: hidden;
  }

  &-list {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding-right: 32px;
    box-sizing: border-box;

    &-info {
      min-height: 89px;
      padding: 24px 0 24px 2px;
      box-sizing: border-box;
      border-bottom: 1px solid #f4f4f4;
      display: flex;
      flex-wrap: wrap;

      &-left {
        width: 50%;
        display: flex;

        &-icon {
          width: 37.6px;
          height: 39.85px;
          margin-right: 16px;

          img {
            width: 100%;
            height: 100%;
          }
        }

        &-content {
          flex: 1;

          .title {
            font-size: 14px;
            color: #262626;
            font-weight: 500;
          }

          .arguments {
            font-size: 12px;
            color: #bfbfbf;
            white-space: nowrap;
            display: flex;
            flex-wrap: wrap;

            span {
              margin-right: 24px;
            }

            a {
              cursor: pointer;
            }
          }
        }
      }

      &-right {
        width: 50%;
        display: flex;
        justify-content: flex-end;

        .width-88 {
          min-width: 88px;
        }

        .width-58 {
          min-width: 58px;
        }
      }
    }

    &-total {
      min-height: 54px;
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;

      &-type {
        width: 95%;
        display: flex;
        flex-wrap: wrap;

        &-item {
          display: flex;
          align-items: baseline;
          flex-wrap: nowrap;
          margin-right: 41px;

          .item-img {
            width: 15px;
            height: 15px;
            line-height: 18px;

            img {
              width: 100%;
            }
          }

          .item-text {
            font-size: 14px;
            color: #595959;
            margin: 0 9px;
            white-space: nowrap;
          }

          .item-num {
            font-size: 14px;
            font-weight: 500;
          }
        }
      }

      &-switch {
        width: 5%;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
</style>
